<template>
  <div class="basicMessage">
    <el-form class="form" :model="basicForm" :rules="reactedRules" ref="basicForm">
      <el-form-item class="formItem move" label="试卷标题" prop="examTitle">
        <el-input v-model="basicForm.examTitle" placeholder="请输入试卷标题" clearable></el-input>
      </el-form-item>
      <el-form-item class="formItem move" label="考试单位" prop="deptId">
        <treeselect 
          :options="dept" 
          :normalizer="normalizer" 
          @select="handleChange" 
          v-model="basicForm.deptId" 
          style="width: 400px;display:inline-block"
          placeholder="请选择考试单位" 
          @keyup.enter.native="crud.toQuery" />
      </el-form-item>
      <el-form-item class="formItem move" label="考试类型" prop="examType">
        <el-select v-model="basicForm.examType" placeholder="请选择考试类型" clearable>
          <el-option
            v-for="item in type"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="formItem move" label="考试时间" prop="timeRange">
        <el-date-picker
          v-model="basicForm.timeRange"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="formItem timelimitMove" label="考试限时(分)" prop="examTimeLimit">
        <!-- <el-input-number v-model="basicForm.timelimit" placeholder="请输入考试限时" clearable></el-input> -->
        <el-input-number v-model="basicForm.examTimeLimit" :min="1" label="请输入考试限时"></el-input-number>
      </el-form-item>
      <el-form-item class="formItem move" label="试卷总分" prop="totalScore">
        <el-input-number v-model="basicForm.totalScore" :min="1" label="请输入试卷总分"></el-input-number>
      </el-form-item>
      <el-form-item class="formItem limitMove" label="答题次数限制" prop="examNumLimit">
        <el-input-number v-model="basicForm.examNumLimit" :min="1" :max="100" label="请输入答题次数限制"></el-input-number>
      </el-form-item>
      <el-form-item class="formItem priceMove" label="考试费用(元)：">
        <!-- <el-input v-model="fee.decimal" disabled style="width:180px"></el-input> -->
        {{fee.decimal}}
        <span v-if="fee.feeType === 1">
          <span class="warningFee">提示：
            <span class="feeTime" v-for="(item,index) in fee.deptPayTime" :key="index">考生在 <span class="warning">{{item.beginTime}}</span> 到 <span class="warning">{{item.endTime}}</span> 期间免费</span>
          </span>
        </span>
      </el-form-item>
      <el-form-item class="formItem priceTypeMove" label="费用类型：">
        <!-- <el-input v-model="fee.feeTypeContend" disabled style="width:180px"></el-input> -->
        {{fee.feeTypeContend}}
      </el-form-item>
      <el-form-item class="formItem move" label="考试介绍" prop="examIntro">
        <!-- <quill-editor class="quillEditor" v-model="basicForm.examIntro" ref="myQuillEditor" :options="editorOption">
        </quill-editor> -->
        <VueEditor
          class="quillEditor"
          ref="myQuillEditor" 
          :options="editorOption"
          useCustomImageHandler
          @image-added="handleImageAdded"
          v-model="basicForm.examIntro"
        ></VueEditor>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" class="button" @click="save('basicForm')">保存</el-button>
        <el-button type="primary" class="button" @click="cancle('basicForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import ExamMessage from '@/api/exam/examMessage'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  quillEditor
} from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import moment from "moment";
import { VueEditor } from "vue2-editor";
import { upload } from "@/utils/upload";
import defaultSettings from "@/settings";
export default {
  name: 'BasicMessage',
  components: {
    Treeselect,
    quillEditor,
    VueEditor
  },
  data(){
    return {
      basicForm: {
        examTitle: '',
        deptId: null,
        examType: null,
        timeRange: [],
        examTimeLimit: 15,
        totalScore: 100,
        examNumLimit: 3,
        examIntro: null,
        beginTime: '',
        endTime: ''
      },
      examId: null,
      dept: [],
      type: [
        {value: 0,label: '入学考试'},
        {value: 1,label: '其他考试'}
      ],
      deptName: '',
      fee: null,
      beginTime: '',
      endTime: '',
      edit: false,
      editorOption: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      reactedRules: {
        examTitle: [
          { required: true, message: '请填写试卷标题', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择考试单位', trigger: 'change' }
        ],
        examType: [
          { required: true, message: '请选择考试类型', trigger: 'change' }
        ],
        timeRange: [
          { required: true, message: '请选择考试时间', trigger: 'change' }
        ],
        examTimeLimit: [
          { required: true, message: '请填写考试限时', trigger: 'blur' }
        ],
        totalScore: [
          { required: true, message: '请填写试卷总分', trigger: 'blur' }
        ],
        examNumLimit: [
          { required: true, message: '请填写次数限制', trigger: 'blur' }
        ],
        examIntro: [
          { required: true, message: '请填写考试介绍', trigger: 'blur' }
        ]
      },
    }
  },
  props: {
    disabledRule: {
      type: Boolean
    },
    basicFormP: {
      type: Object
    },
    isDetailToEdit: {
      type: Boolean,
      default: false
    }
  },
  created() {
    if(this.$route.query){
      console.log(this.$route.query.fee,'this.$route.query.fee 新增或编辑')
      if (this.$route.query.edit === false) {
        this.edit = this.$route.query.edit
        this.fee = JSON.parse(this.$route.query.fee)
        console.log(this.fee,'this.fee')
        this.filter()
      }else if(this.$route.query.edit === true){
        this.edit = this.$route.query.edit
        this.fee = JSON.parse(this.$route.query.fee)
        this.filter()

        this.basicForm = JSON.parse(this.$route.query.basicForm)
        this.basicForm.examTimeLimit = this.basicForm.examTimeLimit/60
        this.$set(this.basicForm, 'timeRange', [this.basicForm.beginTime, this.basicForm.endTime])
      }
    }
  },
  mounted() {
    // 获取部门列表
    ExamMessage.deptCurrent().then(res => {
      let newArr = JSON.parse(
        JSON.stringify(res.data).replace(/name/g, 'label')
      )
      this.dept = newArr
    })
    if(this.isDetailToEdit===true){
      this.basicForm = this.basicFormP
      this.$set(this.basicForm, 'timeRange', [this.basicForm.beginTime, this.basicForm.endTime])
    }
  },
  methods: {
    // 富文本框
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      upload("/api/EToolFile", file).then((res) => {
        // console.log(res.data,'富文本')
        if (res.status === 200) {
          this.editorUrl = defaultSettings.imageUrl + res.data.data.name;
          Editor.insertEmbed(cursorLocation, "image", this.editorUrl);
          resetUploader();
        }
        // if (res.status === 200) {
        //   this.editorImg = res.data.data.name;
        //   this.editorUrl =
        //     process.env.VUE_APP_BASE_API +
        //     "/api/EToolFile/download/picname/" +
        //     this.editorImg;
        //   Editor.insertEmbed(cursorLocation, "image", this.editorUrl);
        //   resetUploader();
        // }
      });
    },
    // fee里面的时间戳转换
    filter(){
      if(this.fee.deptPayTime!==null){
        this.fee.deptPayTime.map(res=>{
          res.beginTime = moment.unix(res.beginTime/1000).format("YYYY-MM-DD HH:mm:ss")
          res.endTime = moment.unix(res.endTime/1000).format("YYYY-MM-DD HH:mm:ss")
        })
      }
      console.log(this.fee,'fee')
    },
    save(basicForm){
      this.$refs[basicForm].validate((valid) => {
        if (valid) {
          // 新增
          if(this.edit === false){
            let params = {
              beginTime : this.basicForm.timeRange[0].getTime(),
              deptId : this.basicForm.deptId,
              endTime: this.basicForm.timeRange[1].getTime(),
              examIntro : this.basicForm.examIntro,
              examNumLimit : this.basicForm.examNumLimit,
              examTimeLimit : this.basicForm.examTimeLimit*60,
              examTitle : this.basicForm.examTitle,
              examType : this.basicForm.examType,
              totalScore : this.basicForm.totalScore
            }
            console.log(params,'新增页面')
            ExamMessage.eExamInfo(params).then(res=>{
              if(res.code===0){
                // ExamMessage.eExamInfoDetail(res.data).then(val=>{
                //   if(val.code===0){
                //     this.$emit("editToDetail",true,val.data)
                //   }
                // })
                this.$refs[basicForm].resetFields();
                // 获取当场考试的id
                this.examId = res.data
                // 试卷规则配置页面不禁用
                this.$emit("openRule",res.data,params.totalScore)
              }
            })
          }else{
            // 编辑
            let params = {
              id: this.basicForm.id,
              beginTime : new Date(this.basicForm.timeRange[0]).getTime(),
              deptId : this.basicForm.deptId,
              endTime: new Date(this.basicForm.timeRange[1]).getTime(),
              examIntro : this.basicForm.examIntro,
              examNumLimit : this.basicForm.examNumLimit,
              examTimeLimit : this.basicForm.examTimeLimit*60,
              examTitle : this.basicForm.examTitle,
              examType : this.basicForm.examType,
              totalScore : this.basicForm.totalScore
            }
            ExamMessage.eExamInfoEdit(params).then(res=>{
              if(res.code===0){
                this.$message({
                  type: 'success',
                  message: '保存成功！'
                });
                // 将新数据传递到详情页
                // ExamMessage.eExamInfoDetail(this.basicForm.id).then(res=>{
                //   if(res.code===0){
                //     this.$emit("editToDetail",true,res.data)
                //   }
                // })
                this.$emit("openRule",this.basicForm.id,this.basicForm.totalScore)
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    cancle(basicForm){
      this.$confirm('是否确定取消', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          this.$message({
            type: 'success',
            message: '取消成功!'
          });
          this.$refs[basicForm].resetFields();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已放弃取消'
          });
        });
    },
    handleChange(value) {
      this.deptName = value.label
      this.deptId = value.id
    },
    normalizer(node) {
      //去掉children=[]的children属性 respectively
      if (node.children && !node.children.length) {
        delete node.children;
      }
    }
  }
};
</script>

<style scoped>
  div>>>.el-input{
    width: 400px;
  }
  div>>>.el-input-number{
    width: 180px;
  }
  div>>>.el-input-number>.el-input{
    width: 180px;
  }
  .basicMessage{
    margin: 10px 0 40px 20px;
  }
  .formItem{
    margin-bottom: 1.25rem;
  }
  .move{
    padding-left: 2em;
  }
  .limitMove{
    padding-left: 4px
  }
  .priceMove{
    padding-left: 12px;
  }
  .timelimitMove{
    padding-left: 9px;
  }
  .priceTypeMove{
    padding-left: 36px;
  }
  .btns{
    padding-left: 110px;
    margin: 20px 0;
  }
  div>>>.el-form-item__error{
    padding-left: 4.75rem;
  }
  div>>>.limitMove .el-form-item__content .el-form-item__error{
    padding-left: 105px;
  }
  /* 富文本 */
  .quillEditor{
    width: 800px;
    height: 400px;
    padding-left: 78px;
  }
  div>>> .ql-toolbar.ql-snow + .ql-container.ql-snow{
    height: 300px;
    overflow: hidden;
  }
  .ql-video {
    position: absolute;
    left: -9999px;
  }
  .ql-editor img {
    width: 100px;
    height: 100px;
  }
  .warning{
    color: red;
  }
  /* 费用提示 */
  .warningFee{
    display: flex;
    flex-wrap: wrap;
    justify-content: left;
    position: relative;
    left: 104px;
  }
  .feeTime{
    flex: 100%;
  }
</style>